package com.alexatguigu.three_conductors_buy_fifty_tickets.counter;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@RestController
@RequestMapping("/alex008")
public class LockDemoController {

    // 计数器
    private int count = 0;
    // 创建可重入锁
    private final Lock lock = new ReentrantLock();

    // Lock方式
    @GetMapping("/lock-count")
    public String lockCount() {
        // lock()必须在try外面，确保获取锁是在try之前
        lock.lock();
        try {
            count++;
            return "Lock计数器当前值: " + count;
        } finally {
            // 必须在finally中释放锁
            lock.unlock();
        }
    }

    // synchronized方式
    @GetMapping("/sync-count")
    public synchronized String syncCount() {
        count++;
        return "Synchronized计数器当前值: " + count;
    }
}